package servlet;

import entity.Passage;
import service.CommonService;
import service.PassageService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@WebServlet( name = "SearchServlet")
public class SearchAllServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用的services
        PassageService passageService = new PassageService();
        CommonService commonService = new CommonService();

        //获取底部信息
        Passage bottomPassage = passageService.getPassageByField("5");
        String bottom_content = (bottomPassage == null) ? "暂无" : bottomPassage.getContent();
        request.setAttribute("bottom_content", bottom_content);

        //获取课程名称
        String courseName = commonService.getCourseName();
        request.setAttribute("courseName" ,courseName);

        //获取搜索信息（字段和page）
        String search = "";
        String page = request.getParameter("page");
        //初次进入，String未转换
        if(page == null)
            search = new String(request.getParameter("searchAll").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        else
            search = (String) request.getAttribute("searchAll");

        //页数相关的其它信息，用于再次分页
        int num_every_page = 10;
        int sum = passageService.getNumberOfSearchPassages(search);
        int last_page = (int) Math.ceil((double)sum / num_every_page);
        if(sum == 0)
            last_page = 1;
        request.setAttribute("sum", sum);
        request.setAttribute("last_page", last_page);

        //转储搜索信息(用于分页时的再次搜索)
        request.setAttribute("search", search);
        request.setAttribute("page",(page == null) ? 1 : Integer.valueOf(page));

        //获取搜索结果
        List<Passage> passages= passageService.getSearchPassages(search, (page == null) ? 1 : Integer.valueOf(page));
        request.setAttribute("passages", passages);


        request.getRequestDispatcher("search_result.jsp").forward(request, response);
    }
}
